package com.sasis.util;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.StringTokenizer;

import org.apache.commons.lang.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * String Utility Class This is used to encode passwords programmatically
 *
 * <p>
 * <a h
 * ref="StringUtil.java.html"><i>View Source</i></a>
 * </p>
 * 
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
public class StringUtil {
    //~ Static fields/initializers =============================================

    private final static Log log = LogFactory.getLog(StringUtil.class);

    //~ Methods ================================================================

    /**
     * Encode a string using algorithm specified in web.xml and return the
     * resulting encrypted password. If exception, the plain credentials
     * string is returned
     *
     * @param password Password or other credentials to use in authenticating
     *        this username
     * @param algorithm Algorithm used to do the digest
     *
     * @return encypted password based on the algorithm.
     */
    public static String encodePassword(String password, String algorithm) {
        byte[] unencodedPassword = password.getBytes();

        MessageDigest md = null;

        try {
            // first create an instance, given the provider
            md = MessageDigest.getInstance(algorithm);
        } catch (Exception e) {
            log.error("Exception: " + e);

            return password;
        }

        md.reset();

        // call the update method one or more times
        // (useful when you don't know the size of your data, eg. stream)
        md.update(unencodedPassword);

        // now calculate the hash
        byte[] encodedPassword = md.digest();

        StringBuffer buf = new StringBuffer();

        for (int i = 0; i < encodedPassword.length; i++) {
            if ((encodedPassword[i] & 0xff) < 0x10) {
                buf.append("0");
            }

            buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
        }

        return buf.toString();
    }

    /**
     * Encode a string using Base64 encoding. Used when storing passwords
     * as cookies.
     *
     * This is weak encoding in that anyone can use the decodeString
     * routine to reverse the encoding.
     *
     * @param str
     * @return String
     */
    public static String encodeString(String str)  {
        sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
        return encoder.encodeBuffer(str.getBytes()).trim();
    }

    /**
     * Decode a string using Base64 encoding.
     *
     * @param str
     * @return String
     */
    public static String decodeString(String str) {
        sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
        try {
            return new String(dec.decodeBuffer(str));
        } catch (IOException io) {
        	throw new RuntimeException(io.getMessage(), io.getCause());
        }
    }
    
    /**
     * ADD BY KELLEN 
     * 06-12-20
     */
	public static boolean isEmpty(String str){
		if(null==str){
			return true;
		}else if("".equalsIgnoreCase(str)){
			return true;
		}else return false;
	}
	
	public static String getPrefix(String str,int prefix){
		String prefixx = str;
		if(!isEmpty(str)){
			prefixx = str.substring(0,prefix);
		}
		return prefixx;
	}
	
	public static String getBackfix(String str,int prefix){
		String prefixx = str;
		if(!isEmpty(str)){
			prefixx = str.substring(prefix);
		}
		return prefixx;
	}
	
	public static boolean isValidMobile(String mobile){
		return !StringUtil.isEmpty(mobile ) && 
		NumberUtils .isDigits(mobile) &&
		(mobile.length() == 11);
	}
	/**
	 * author:kellen
	 * modified date:07-03-01
	 * email address validate
	 * @param aEmailAddress
	 * @return
	 */
	public static boolean isValidEmail(String aEmailAddress){
	    if (aEmailAddress == null) return false;
	    
	    boolean result = true;
	     
	    if ( ! hasNameAndDomain(aEmailAddress) ) {
	    	result = false;
	    }
	    
	    return result;
	  }
	  
	private static boolean hasNameAndDomain(String aEmailAddress){
	    String[] tokens = aEmailAddress.split("@");
	    return 
	     tokens.length == 2 &&
	     !StringUtil.isEmpty( tokens[0] ) && 
	     !StringUtil.isEmpty( tokens[1] ) &&
	     -1!=tokens[1].indexOf(".");
	  }
 
	 public   static   String   constructSql   (String   sql,Object[]   array)   {   
	    	String from="?";
			StringBuffer bf= new StringBuffer("");
			int   i   =   0; 
			StringTokenizer st = new StringTokenizer(sql,from,true);
			while (st.hasMoreTokens())
			{
				String tmp = st.nextToken();
			 
				if(tmp.equals(from))
				{
					bf.append(String.valueOf(array[i]));
					i++;
				}
				else
				{
					bf.append(tmp);
				}
			}
			return bf.toString();
	    }
	    
 
 
    
	public static void main(String[] args){
		// String   sql   =   "select   *   from   groupform   where   groupid=?   order=?   by   desc";   
	       // String[]   array   =   {"1","2"};   
	       // System.out.println(str_replace("?",array,sql));   
		System.out.println(">>>>>>>>>>>>>>>>>");
	}
}
